import { Component, ChangeDetectorRef, Host, ChangeDetectionStrategy } from "@angular/core";
import { AppComponent } from "../../../../../../app.component";
import { CompanyService } from "../../../company.service";
import { Subscription } from "rxjs";
import { ActivatedRoute } from "@angular/router";
import { CompanyControversiesService } from "../../companyControversies.service";
import { ControversyQualitativePerformanceModel } from "../../../../../../shared/models/qualitativePerformance.model";
import { environment } from "../../../../../../../environments/environment";
import { ChartBenchmarkModel } from "../../../riskRating/templates/subIndustry/models/chartBenchmark.model";
import { ControversyGroupModel } from "./models/controversyGroup.model";
import { BaseComponent } from "../../../../../../shared/components/baseComponent/base.component";
import { ClusterModelWrapper } from "../../../../riskCluster/cluster.model";
import { UtilsService } from "../../../../../../shared/services/utils.service";

/**
 * Controversy incident component
 *
 * Author: Sorin Spiru
 * Date: 14.03.2018
 *
 * TODO: custom chart tooltip and legend
 */
@Component({
    moduleId: module.id,
    templateUrl: 'controversiesIncidents.component.html',
    styleUrls: [
        '../../../company.component.scss',
        '../../companyControversies.component.scss'
    ],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ControversiesIncidentsComponent extends BaseComponent {
    private sub: Subscription;
    private number: string;
    public readonly resourcesUrl: string = environment.resourcesUrl;
    public incidents: ControversyQualitativePerformanceModel;
    public highestIncidentOutlookAssessment: string;
    public chartData: ChartBenchmarkModel[];
    public companyId: string;

    private categories: ClusterModelWrapper[] = [
        new ClusterModelWrapper(0, '0', 'None', 'None', '#F0AB01', 16),
        new ClusterModelWrapper(1, '1', 'Category 1', 'Cat 1', '#F3BC33', 32),
        new ClusterModelWrapper(2, '2', 'Category 2', 'Cat 2', '#F6CD66', 48),
        new ClusterModelWrapper(3, '3', 'Category 3', 'Cat 3', '#F9DD99', 64),
        new ClusterModelWrapper(4, '4', 'Category 4', 'Cat 4', '#FCEDCC', 80),
        new ClusterModelWrapper(5, '5', 'Category 5', 'Cat 5', '#FCEDCC', 100)
    ];


    constructor(
        private route: ActivatedRoute,
        private cdRef: ChangeDetectorRef,
        private companyService: CompanyService,
        private companyControversiesService: CompanyControversiesService,
        @Host() private rootComponent: AppComponent) {
            super(cdRef);
    }

    ngOnInit() {
        this.sub = this.route.params.subscribe(params => {
            this.chartData = [];
            this.number = params['number'] as string;
            this.companyService.company.subscribe(company => {
                this.companyId = company.id;
                this.companyControversiesService.controviersiesTheme.subscribe(incidentsbyTheme => {
                    //get incidents details
                    this.incidents = incidentsbyTheme.filter(x => x.number == this.number)[0];

                    var highestIncidentOutlookScore = 0;
                    var eventIndicators =  this.incidents.eventIndicators.filter(ev=> ev.answerCategory == this.incidents.answerCategory);
                    eventIndicators.forEach(eventIndicator =>{
                        if(eventIndicator.outlookScore != null && eventIndicator.outlookScore != highestIncidentOutlookScore)
                        {
                            if(eventIndicator.outlookScore == -1)
                                {highestIncidentOutlookScore = eventIndicator.outlookScore;}
                                else if (eventIndicator.outlookScore == 1 && highestIncidentOutlookScore != -1)
                                {highestIncidentOutlookScore = eventIndicator.outlookScore;}
                        }
                    })
                    switch (highestIncidentOutlookScore)
                    {
                        case -1:
                            this.highestIncidentOutlookAssessment =  "Negative";break;
                        case 0:
                            this.highestIncidentOutlookAssessment =  "Neutral";break;
                        case 1:
                            this.highestIncidentOutlookAssessment =  "Positive";break;
                        default:
                            this.highestIncidentOutlookAssessment = "";break;
                    }


                    this.companyControversiesService.comparison.subscribe(comparison => {
                        let currentCategory: ControversyGroupModel;
                        Object.keys(this.categories).forEach(key => {
                            currentCategory = comparison.filter(x => {
                                return x.controversyIndicatorNumber == this.number &&
                                    x.category.toString() == key;
                            })[0];

                            this.chartData.push(
                                new ChartBenchmarkModel(
                                    this.categories[key],
                                    currentCategory ? currentCategory.percent : 0,
                                    key == this.incidents.answerCategory.toString() ? "#FCAF17" : "#888888",
                                    false
                                )
                            )
                        });
                        this.cdRef.markForCheck();
                    }, error => this.errorCallback(_ => { this.chartData = undefined; }, error))

                    this.cdRef.markForCheck();
                    this.rootComponent.finishLoading();
                }, error => this.errorCallback(_ => { this.incidents = undefined; }, error));
            });
        });
    }

    ngOnDestroy() {
        this.sub.unsubscribe();
    }

    get incidentIconPath(): string {
        return UtilsService.getIconFilename(this.incidents.name, 'controversies');
    }
}